<template>
	<view :class="theme">
		<view class="user-top">
			<view class=" flex align-center justify-between margin-top-sm">
				<view class="flex align-center">
					<view class='cu-avatar round lg ov-h'>
						<image v-if="userInfo.avatar" :src="userInfo.avatar" mode="aspectFit"></image>
						<image v-else :src="`${$hd.baseUrl}/images/flyer.png`" mode="aspectFit"></image>
					</view>
					<view class="margin-left-sm text-white">
						<view class=" text-bold text-lg">
							{{ userInfo.name }}
						</view>
						<view class=" margin-top-xs">
							{{ mobile }}
						</view>
					</view>
				</view>
				<view class="text-white">
					评分：
					<text class="text-bold">{{ userInfo.score?userInfo.score:0 }}</text>
				</view>

			</view>
		</view>

		<view class="info-box margin">
			<view class="bg-white flex padding  radius-lg ov-h">
				<view class="bg-us flex-sub margin-right flex align-end padding radius"
					@click="jumpOrder(theme == 'fs'?'1':'0')">
					<view class="flex-sub ">
						<view class="text-bold text-black">
							{{publicOrder}}
						</view>
						<view class="text-sm text-gray margin-top-xs">
							{{theme == 'fs'? '完成公海订单' : '预约下单数'}}
						</view>
					</view>
					<view class="margin-left">
						<image class="ds-img" :src="`${$hd.baseUrl}/images/icon-ghorder.png`" mode="aspectFit"></image>
					</view>
				</view>
				<view class="bg-us flex-sub flex align-end padding radius" @click="jumpOrder(theme == 'fs'?'0':4)">
					<view class="flex-sub ">
						<view class="text-bold text-black">
							{{assignOrder}}
						</view>
						<view class="text-sm text-gray margin-top-xs">
							{{theme == 'fs'? '完成指派订单' : '完成订单数'}}
						</view>
					</view>
					<view class="margin-left">
						<image class="ds-img" :src="`${$hd.baseUrl}/images/icon-zporder.png`" mode="aspectFit"></image>
					</view>
				</view>
			</view>

			<view
				class="margin-top padding-lr padding-tb-lg flex align-center justify-between bg-white  radius-lg ov-h">
				<view class="text-center text-gray" @click="setUserInfo">
					<image class="img-mn" :src="`${$hd.baseUrl}/images/${theme}/icon-set.png`" mode="aspectFit"></image>
					<view class="text-sm">
						个人设置
					</view>
				</view>
				<view class="text-center text-gray" @click="onAuth">
					<image class="img-mn" :src="`${$hd.baseUrl}/images/${theme}/icon-certification.png`"
						mode="aspectFit">
					</image>
					<view class="text-sm">
						{{theme == 'fs'? '飞手入驻' : '用户认证'}}
					</view>
				</view>
				<view class="text-center text-gray" @click="onUse">
					<image class="img-mn" :src="`${$hd.baseUrl}/images/${theme}/icon-terms.png`" mode="aspectFit">
					</image>
					<view class="text-sm">
						使用条款
					</view>
				</view>
				<view class="text-center text-gray" @click="onClause">
					<image class="img-mn" :src="`${$hd.baseUrl}/images/${theme}/icon-privacy.png`" mode="aspectFit">
					</image>
					<view class="text-sm">
						隐私政策
					</view>
				</view>
				<!-- 待确认收款 -->
				<view v-if="theme == 'fs'" class="text-center text-gray relative" @click="onConfirmPayment">
					<image class="img-mn" :src="`${$hd.baseUrl}/images/fs/icon-payment.png`" mode="aspectFit" />
					<view v-if="pendingTransfers.length > 0" class="badge-count">
						{{ pendingTransfers.length }}
					</view>
					<view class="text-sm">待确认收款</view>
				</view>
			</view>
		</view>
		<view class="bottom-btn">
			<uv-button text="退出登录" size="normal" :color="theme == 'fs'? '#006BFE' : '#0CCA89'" @tap="showModal"
				data-target="DialogModal1" />
		</view>

		<view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar justify-end">
					<view class="content">提示</view>
				</view>
				<view class="padding-xl" style="color: darkgray">
					确定退出？
				</view>
				<view class="cu-bar justify-center">
					<view class="action">
						<button class="cu-btn " :class="theme == 'fs'? 'text-blue line-blue': 'text-green line-green'"
							@tap="hideModal">取消</button>
						<button class="cu-btn bg-green margin-left" :class="theme == 'fs'? 'bg-main': 'bg-green'"
							@click="logout">确定</button>
					</view>
				</view>
			</view>
		</view>

		<TabBar current="mine"></TabBar>
	</view>
</template>

<script>
	import TabBar from '@/components/tabBar/index.vue'
	import {
		mapGetters
	} from 'vuex'

	export default {
		components: {
			TabBar
		},
		computed: {
			...mapGetters(['theme', 'userInfo'])
		},
		data() {
			return {
				// userInfo: {},
				modalName: "",
				publicOrder: 0,
				assignOrder: 0,
				mobile: "",
				pendingList: [],
				// 待收款列表
				pendingTransfers: [],
				pendingPackageInfo: '',
				mchId: '',
			}
		},
		async onShow() {
			// 刷新用户信息
			this.$store.dispatch('user/setUserAction')
			if (this.theme == 'farmer') {
				uni.setNavigationBarColor({
					backgroundColor: '#0BCA89',
					frontColor: '#ffffff'
				});
			} else {
				uni.setNavigationBarColor({
					backgroundColor: '#006BFE',
					frontColor: '#ffffff',
				});
			}
			const _this = this;
			this.fetchOrderSum();
			this.getFlyAudit();
			// 待收款列表
			this.fetchPendingTransfers();
			// 获取商户号
			this.$http.get('/system/config/list?configKey=mch-id').then(res => {
				uni.hideLoading()
				if (res.code == 200 && res.rows.length > 0) {
					this.mchId = res.rows[0].configValue
				}
			})
			// try {
			// 	const user = await this.$hd.isLogin();
			// 	// 测试检测未登录，跳转到登录页
			// 	if (!user) {
			// 		_this.login()
			// 	} else {
			// 		// 当前用户信息
			// 		_this.userInfo = {}
			// 		_this.userInfo = user
			// 		if (user.user.avatar) {
			// 			_this.userInfo.avatar = this.$hd.baseUrl + '/common/file/' + user.user.avatar
			// 		}
			// 		this.fetchOrderSum();
			// 		this.getFlyAudit();
			// 		// 待收款列表
			// 		this.fetchPendingTransfers();
			// 	}
			// } catch (error) {
			// 	console.log(error)
			// 	_this.login()
			// }

		},
		methods: {
			async onConfirmPayment() {
				if (!this.pendingPackageInfo) {
					return uni.$uv.toast('暂无待确认收款');
				}
				wx.requestMerchantTransfer({
					mchId: this.mchId,
					appId: wx.getAccountInfoSync().miniProgram.appId,
					package: this.pendingPackageInfo,
					success: (res) => {
						console.log('转账发起 success:', res);
						// 再调用后端接口查询状态
						const outBillNo = this.pendingTransfers[0].outBillNo;
						this.$http
							.get(`/cadre/highSeasOrder/transfer/status/${outBillNo}`)
							.then(statusRes => {
								if (statusRes.code === 200) {
									console.log('已确认收款', statusRes.data);
									// 刷新待收款列表
									this.fetchPendingTransfers();
								}
							});
					},
					fail: (err) => {
						console.log('转账发起 fail:', err);
					},
				});
			},

			setUserInfo() {
				// uni.navigateTo({
				// 	url: '/pages/userInfo/index',
				// })
				uni.$uv.route('/subPages/pages/userInfo/index');
			},
			onAuth() {
				if (this.theme == 'fs') {
					uni.$uv.route('/subPages/pages/authInfo/index');
				} else {
					uni.$uv.route('/subPages/pages/authInfo/FarmerAuth');
				}
			},
			onUse() {
				uni.$uv.route('/subPages/pages/useClause/index');
			},
			onClause() {
				uni.$uv.route('/subPages/pages/useClause/index');
			},
			login() {
				uni.navigateTo({
					url: "/pages/public/login"
				})
			},
			showModal(e) {
				this.modalName = 'DialogModal1'
			},
			hideModal(e) {
				this.modalName = null
			},
			logout() {
				this.$http.post('/logout').then(res=>{
					uni.removeStorageSync('token');
					uni.removeStorageSync('formData');
				})
				// uni.removeStorageSync('login-type');
				// uni.removeStorageSync('userInfo');
				this.$store.dispatch('user/cleanUserAction')
				this.hideModal()
				uni.navigateTo({
					url: "/pages/public/login"
				})
			},
			// 待收款列表
			fetchPendingTransfers() {
				this.$http.get('/cadre/highSeasOrder/transfer/pending').then(res => {
					if (res.code === 200 && Array.isArray(res.data)) {
						this.pendingTransfers = res.data;
						if (res.data.length > 0) {
							this.pendingPackageInfo = res.data[0].packageInfo;
						} else {
							this.pendingPackageInfo = '';
						}
					} else {
						this.pendingTransfers = [];
            			this.pendingPackageInfo = '';
					}
				}).catch(error => {
					this.pendingTransfers = [];
					this.pendingPackageInfo = '';
					console.error('获取待收款列表失败:', error);
				});
			},
			getFlyAudit() {
				let _this = this;
				_this.$http.get('/cadre/flyerAudit/getInfoApp').then(res => {
					if (res.data.contact == null || res.data.contact === '') {
						_this.mobile = _this.userInfo.contact;
					} else {
						_this.mobile = res.data.contact;
					}
				})
			},
			fetchOrderSum() {
				this.$http.get(this.theme == 'fs' ? '/cadre/assignOrder/ordersSum' : '/cadre/highSeasOrder/ordersSum', {
					params: {
						flyerld: this.userInfo.id
					}
				}).then(res => {
					this.publicOrder = res.data.publicOrder
					this.assignOrder = res.data.assignOrder
				})
			},
			jumpOrder(v) {
				uni.setStorageSync('orderTab', v)
				// uni.$uv.route('/pages/order/index');
				uni.switchTab({
					url: '/pages/order/index?orderTab=' + v
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.bottom-btn {
		position: absolute;
		width: 100%;
		padding: 5%;
		height: 10rpx;
		bottom: 150px;
	}

	.user-top {
		background-color: #006BFE;
		padding: 20rpx 40rpx 50rpx;
		height: 300rpx;
		border-bottom-left-radius: 50%;
		border-bottom-right-radius: 50%;
	}

	.info-box {
		position: relative;
		top: -160rpx;
	}

	.ds-img {
		width: 64rpx;
		height: 64rpx;
	}

	.img-mn {
		width: 48rpx;
		height: 48rpx;
	}

	.bottom-wrap {
		height: 50px;
	}

	.fs {
		.user-top {
			background-color: #006BFE;
		}

		.bg-us {
			background-color: #F3F6FA;
		}
	}

	.farmer {
		.user-top {
			background-color: #0BCA89;
		}

		.bg-us {
			background-color: #DBFFF3;
		}
	}

	// 待收款角标
	.relative {
		position: relative;
	}

	// 待收款角标
	.badge-count {
		position: absolute;
		top: -4rpx;
		right: -4rpx;
		background-color: red;
		color: #fff;
		font-size: 20rpx;
		border-radius: 50%;
		padding: 4rpx 10rpx;
		min-width: 28rpx;
		text-align: center;
		line-height: 1;
		z-index: 10;
	}
</style>